//
//  SurveyViewController.swift
//  LongTermInsurance
//
//  Created by DYD on 2018/11/22.
//  Copyright © 2018 HeChao. All rights reserved.
//

import UIKit
import ObjectMapper
class SurveyViewController: BaseViewController {
    
    

    @IBOutlet weak var descLabel: UILabel!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var confirmButton: UIButton!
    
    var dataSource = [SurveyModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "自测题"
        
        // Do any additional setup after loading the view.
        tableView.backgroundColor = UIColor.hexString(hexString: "#EEF1EE")
        collectionView.backgroundColor = UIColor.hexString(hexString: "#EEF1EE")
        
        tableView.delegate = self
        tableView.dataSource = self
        collectionView.dataSource = self
        collectionView.delegate = self
        tableView.tableFooterView = UIView()
        tableView.register(UINib(nibName: "ConnectWithTableViewCell", bundle: nil), forCellReuseIdentifier: "ConnectWithTableViewCell")
        collectionView.register(UINib(nibName: "SurveyItemNOCell", bundle: nil), forCellWithReuseIdentifier: "SurveyItemNOCell")
        
        descLabel.text = "尊敬的申请人： \n   本《自测表》是您的长期护理保险档案的真实记录之一，请您认真逐项如实测评；如经查实存在不实情况，将记录申请人的不诚信息，并追究相应的法律责任。 \n   若您的自测结果为中毒依赖或者重度依赖，才可以进入申请流程！"
        
        getSurveyData()
    }
    
    func getSurveyData() {
        
        //        let values = ["IDNum": idString,"Password": pwdString].convertToJsonString()
        //        let p0 = "<CodeName>"+"loginapp"+"</CodeName>"
        //        let p1 = "<json>"+values+"</json>"
        
        let paramString = ""
        
        NetworkingHandle.fetchNetworkData(method: "getTestSelfTitle", paramString: paramString, success: { (dict) in
            if let count = dict["Count"] as? Int,count > 0 {
                
                guard let titleArrayString = dict["Titles"] as? String else {
                    return
                }
                guard let titleArray = Mapper<SurveyModel>().mapArray(JSONString: titleArrayString) else {
                    return
                }
                
                guard let itemArrayString = dict["Keys"] as? String else {
                    return
                }
                guard let itemArray = Mapper<SurveyItem>().mapArray(JSONString: itemArrayString) else {
                    return
                }
                print("")
                
                let newTitleArray = titleArray.map({ (model) -> SurveyModel in
                    let newItemList = itemArray.filter{
                        $0.titleNO == model.titleNO
                    }
                    model.surveyArray = newItemList
                    #if DEBUG
                    
                    model.selectIndex = 3
                    
                    #endif
                    
                    return model
                })
                self.dataSource = newTitleArray
                self.tableView.reloadData()
                self.collectionView.reloadData()
            }
            
        }) {
            print("")
        }
        
    }
    
    @IBAction func nextButtonAction(_ sender: UIButton) {
        
        guard let info = MyselfSingleton.shared.userInfo else {
            makeToast("请重新登录")
            return
        }
        
        guard dataSource.count > 0 else {
            return
        }
        var shouldReturn = false
        let dataArray = dataSource.map { (model) -> Dictionary<String, Any> in
            if model.selectIndex == 0 || model.surveyArray.count < model.selectIndex {
                shouldReturn = true
                return ["": ""]
            }
            var data = [String: Any]()
            data["TitleNo"] = model.titleNO
            data["KeyNo"] = model.surveyArray[model.selectIndex - 1].itemNO

            return data
        }
        
        guard !shouldReturn else {
            return
        }
        
        
        
        let dict = ["InsuranceNo": info.personNum,
                     "KeyDetail": dataArray.convertToJsonString(),
                     "PersionID": info.userID] as [String : Any]
        let paramString = dict.convertToJsonString()
        
        let param = "<json>"+paramString+"</json>"
        
        NetworkingHandle.fetchNetworkData(method: "saveTestSelfInfo", paramString: param, success: { [weak self] (dict) in
            if let code = dict["ResultCode"] as? Int,code == 0 {
                guard let testNum = dict["TestNum"] as? Int else {
                    return
                }
                guard let standarNum = dict["standardNum"] as? Int else {
                    return
                }
                if testNum >= standarNum {
                    self?.makeToast("您的评估分数为\(testNum),不可申请", durations: ToasterDelay.long)
                } else {
                    self?.showNextAlert()
                }
                return
            }
            if let code = dict["ResultCode"] as? Int,code == 1 {
                if let msgString = dict["ResultMessage"] as? String {
                    CDUtility.showMSG(message: msgString)
                }
            }
        }) {
            print("")
        }
        
    }
    
    func showNextAlert() {
        let alert = UIAlertController(title: "提交成功", message: "是否进行下一步", preferredStyle: .alert)
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let action = UIAlertAction(title: "确定", style: .default) { (action) in
            
            let vc = ApplyMenuViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
        alert.addAction(cancel)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
    
    
}

extension SurveyViewController: UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ConnectWithTableViewCell", for: indexPath) as! ConnectWithTableViewCell
        let model = dataSource[indexPath.row]
        cell.model = model
        
        cell.block = {[weak self] in
            self?.collectionView.reloadData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 230
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SurveyItemNOCell", for: indexPath) as! SurveyItemNOCell
        cell.titleLabel.text = "\(indexPath.item + 1)"
        let model = dataSource[indexPath.row]
        cell.titleLabel.backgroundColor = model.selectIndex == 0 ? UIColor.white : CDColor.themePink
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 20.0, height: 20.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
    }
}
